<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"/>
    <!-- <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">-->
    <title>虚线</title>
</head>
<body>
<!--<canvas id="canvas"></canvas>
当画布的id为canvas时，浏览器默认自动获取画布的实例，并设为全局变量，变量名为canvas
-->
<canvas id="animCanvas"></canvas>
<p></p>
<canvas id="normalCanvas1"></canvas>
<canvas id="normalCanvas2"></canvas>
<p></p>
<canvas id="lookLineCanvas"></canvas>
<script>
    function drawAnim() {
        var canvas = document.getElementById('animCanvas');
        var ctx = canvas.getContext('2d');
        var offset = 0;

        function draw() {

            ctx.clearRect(0, 0, canvas.width, canvas.height);
            //来指定线段与间隙的交替
            ctx.setLineDash([4, 2]);
            // 属性设置起始偏移量
            ctx.lineDashOffset = -offset;
            //不填充，只绘制线框
            ctx.strokeRect(10, 10, 100, 100);
            // console.log(offset);
        }

        function march() {
            offset++;
            if (offset > 16) {
                offset = 0;
            }
            draw();
            //递归，绘制，产生动画
            setTimeout(march, 20);
        }

        march();
    }

    function drawNormal() {

        function drawNormal1() {

            var canvas = document.getElementById('normalCanvas1');
            var ctx = canvas.getContext('2d');
            var offset = 10;

            ctx.clearRect(0, 0, canvas.width, canvas.height);
            //来指定线段与间隙的交替
            ctx.setLineDash([20, 10]);
            // 属性设置起始偏移量，向x负轴方向偏移
            ctx.lineDashOffset = offset;
            //不填充，只绘制线框
            ctx.strokeRect(10, 10, 250, 100);

            ctx.fillText("线段："+ctx.getLineDash()[0]+" 空白间隙："+ctx.getLineDash()[1],100,75);

        }

        function drawNormal2() {

            var canvas = document.getElementById('normalCanvas2');
            var ctx = canvas.getContext('2d');
            var offset = 0;

            ctx.clearRect(0, 0, canvas.width, canvas.height);
            //来指定线段与间隙的交替数组
            ctx.setLineDash([10, 20]);
            // 属性设置起始偏移量
            ctx.lineDashOffset = offset;
            //不填充，只绘制线框
            ctx.strokeRect(10, 10, 250, 100);
            ctx.fillText("线段："+ctx.getLineDash()[0]+" 空白间隙："+ctx.getLineDash()[1],100,75);
        }

        drawNormal1();
        drawNormal2();
    }

    function drawLookLine(){
        var canvas = document.getElementById("lookLineCanvas");
        var ctx = canvas.getContext("2d")

        ctx.moveTo(10,10);
        ctx.lineTo(30,10);
        ctx.moveTo(10,20);
        ctx.lineTo(20,20);
        ctx.stroke();

    }
    drawAnim();
    drawNormal();
    drawLookLine();

</script>
</body>
</html>
